package com.eugeneMa.service.impl;

import com.eugeneMa.dao.UserInfoDao;
import com.eugeneMa.entity.Result;
import com.eugeneMa.entity.UserInfo;
import com.eugeneMa.enumEntity.ErrorMsg;
import com.eugeneMa.service.inter.LoginService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;


/**
 * 登录业务层
 *
 * @author Eugenema
 * @date 2022/2/13 9:21
 */
@Service
public class LoginServiceImpl implements LoginService {
    /** 日志 */
    private Logger logger = Logger.getLogger(LoginServiceImpl.class);
    /** 用户Dao */
    @Autowired
    private UserInfoDao userInfoDao;

    /**
     * 登录：校验用户名和密码是否正确
     *
     * @author Eugenema
     * @date 2022/2/13 9:22
     *
     * @param userName     用户名
     * @param userPassword 用户密码
     *
     * @return 登录结果，若正确，则携带用户信息。反之null
     **/
    @Override
    public Result login(String userName, String userPassword) {
        //判断用户是否存在
        UserInfo userInfo = userInfoDao.queryUserByName(userName);
        if (userInfo == null) {
            return new Result(false, null, ErrorMsg.USER_NO_EXISTS);
        }
        //判断密码是否正确
        if (!BCrypt.checkpw(userPassword, userInfo.getUserPassword())) {
            return new Result(false, null, ErrorMsg.USERNAME_PASSWORD_ERROR);
        }
        return new Result(true, userInfo, null);
    }

    /**
     * 注册
     *
     * @author Eugenema
     * @date 2022/2/27 17:28
     *
     * @param userName 用户名
     * @param userPassword 密码
     *
     * @return 注册结果
     **/
    @Override
    public Result register(String userName, String userPassword) {
        //判断用户是否存在
        UserInfo userInfo = userInfoDao.queryUserByName(userName);
        if (userInfo != null) {
            return new Result(false, null, ErrorMsg.USERNAME_SAME);
        }

        //加密密码
        String salt = BCrypt.gensalt();
        userPassword = BCrypt.hashpw(userPassword, salt);
        //新增用户
        int rows = userInfoDao.insertUser(userName, userPassword);

        if (rows < 1) {
            return new Result(false, null, ErrorMsg.SYSTEM_ERROR);
        }
        return new Result(true, null, null);
    }
}
